package com.ljsw.fragment;

import java.io.Serializable;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ljsw.activity.R;
import com.ljsw.adapter.RenWuAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.TiShiDialog;
import com.ljsw.entity.RenWuClass;
import com.ljsw.fragment.MyRenwuFragment.MyRwListener;
import com.ljsw.server.UpServer;
import com.ljsw.util.DialogManager;
import com.ljsw.util.Table;
/**
 * 任务完成 fragment
 * 作者: 石锚
 * 版本: 1.0
 * 日期: 2015-10-16
 */
public class RwwcFragment extends BaseFragment implements OnClickListener,OnItemClickListener{
	public static final String state ="1";//标识已完成的任务的状态
	private TextView back,zx_carId,shuaxin;//退出  车牌号 刷新
	private LoginDialog dialog;
	private DeleteDialog deleteDialog;//删除Dialog
	private DialogManager dmanager;//提示管理器
	private TiShiDialog tDialog;//友情提示
	private Handler handler;
	private Button huiku;
	private App app;
	private View view;
	private ListView wanceng_list;//任务完成
	private RenWuAdapter adapter;//任务完成适配器
	private List<String> listBox = new ArrayList<String>();//周转箱集合
	private ArrayList<RenWuClass> wancenglist = new ArrayList<RenWuClass>();//任务完成集合
	private boolean flag = false;//刷新控制
	private String str;//车牌号接口返回的字符串
	private String box ;//周转箱
	Table[] tables;
	private FragmentManager fm;
	public final static int TAG=4;
	private OnLoadZhuangXiangView listener;//装箱数量回调接口
	public interface OnLoadZhuangXiangView{
		public void onloadCount(int count);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_renwuwancheng, container,false);
		app = (App) getActivity().getApplication();
		fm = getFragmentManager();
		dmanager = new DialogManager(getActivity());
		dialog = dmanager.getLoginDialog();
		deleteDialog = dmanager.getDeleteDialog();
		tDialog = dmanager.getTiShiDialog();
		initView();
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				dialog.dismiss();
				switch (msg.what) {
					case 0:
						//视图显示
						showView();
						listener.onloadCount(adapter.getCount());
						break;
					case 1://加载为空值
						//Toast.makeText(getActivity(), "没有完成的任务", Toast.LENGTH_LONG).show();
						break;
					case 2://连接超时
						OnClick();
						deleteDialog.setTitle("网络连接超时");
						break;
					case 3://加载异常
						OnClick();
						deleteDialog.setTitle("加载异常");
						break;
					case 5:
						tDialog.show();
						tDialog.setMessage("没有获取到任务");
						new Thread(new Runnable() {

							public void run() {
								// TODO Auto-generated method stub
								try {
									Thread.sleep(1000);
									handler.sendEmptyMessage(6);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();
						break;
					case 6:
						tDialog.dismiss();
						break;
					case 4:
						//传递信息
						passBox();
						break;
				}
			}
		};
		return view;
	}
	/**
	 * 初始化控件
	 */
	public void initView(){
		zx_carId = (TextView) view.findViewById(R.id.zx_carId);
		back = (TextView) getActivity().findViewById(R.id.back);
		shuaxin = (TextView) getActivity().findViewById(R.id.shuaxin);
		huiku = (Button) view.findViewById(R.id.huiku);
		wanceng_list = (ListView) view.findViewById(R.id.wanceng_list);
		wanceng_list.setOnItemClickListener(this);
		shuaxin.setOnClickListener(this);
		huiku.setOnClickListener(this);
		back.setOnClickListener(this);
		zx_carId.setText(app.cardId);
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}
	@Override
	public void onStart() {
		super.onStart();
		flag = true;
		if(app.back.equals("back")){
			back.setText("返回");
		}else{
			back.setText("返回");
		}
		if(adapter == null){
			adapter = new RenWuAdapter(getActivity(), wancenglist);
		}
		listener.onloadCount(adapter.getCount());
		wancenglist.clear();
		if(wancenglist.size()==0 && app.cardId!=null){
			loadWancengRenwu();
		}
		wanceng_list.setAdapter(adapter);

	}
	@Override
	public void onAttach(Activity activity) {
		try {
			listener = (OnLoadZhuangXiangView) activity;
		} catch (Exception e) {
		}
		super.onAttach(activity);
	}

	/**
	 * 加载任务完成数据
	 */
	public void loadWancengRenwu(){
		dialog.show();
		dialog.setMessage("获取我的任务中...");
		new Thread(new Runnable() {
			public void run() {
				try {
					if(app.cardId !=null && !"".equals(app.cardId)){
						str = UpServer.getRenwuList(app.cardId,state,app.userZhanghao);
						if(!"".equals(str) && null!= str){
							handler.sendEmptyMessage(0);//成功
						}else{
							handler.sendEmptyMessage(1);//没有任务
						}
					}else{
						handler.sendEmptyMessage(5);//没有车牌号
					}

				} catch (SocketException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(2);//超时链接
				}catch (NullPointerException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(1);//没有任务
				}catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(3);//其他异常
				}
			}
		}).start();
	}

	/**
	 * 加载失败是重试方法
	 */
	public void OnClick(){
		deleteDialog.show();
		deleteDialog.setPositiveButton("确定", new OnClickListener() {
			public void onClick(View arg0) {
				loadWancengRenwu();
			}
		}).setNegativeButton("取消", new OnClickListener() {
			public void onClick(View arg0) {
			}
		});
	}
	/**
	 * 点击刷新
	 */
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
			case R.id.shuaxin://刷新
				if(flag){
					loadWancengRenwu();
				}
				break;
			case R.id.huiku:
				getBox();
				break;
			case R.id.back:
//				控制 返回时 一推到低
//				for (int i = 0; i < fm.getBackStackEntryCount(); i++) { 改动
//					fm.popBackStack();
//				}
				if(getActivity()!=null){
					getActivity().onBackPressed();
				}
				break;
		}
	}
	@Override
	public void onStop() {
		flag = false;
		super.onStop();
	}
	/**
	 * 根据车牌号获取周转箱
	 */
	public void getBox(){
		dialog.show();
		dialog.setMessage("周转箱获取中...");
		new Thread(new Runnable() {
			public void run() {
				try {
					box = UpServer.getReturnZhouZhuanXiang(app.cardId);
					if(!"".equals(box) && null!=box){
						handler.sendEmptyMessage(4);//成功
					}else{
						handler.sendEmptyMessage(5);
					}
				} catch (SocketException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(6);
				}catch (NullPointerException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(5);
				}catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(7);
				}
			}
		}).start();
	}
	/**
	 * 显示视图
	 */
	public void showView(){
		if ("车牌号不存在".equals(str)) {
			Toast.makeText(getActivity(), "没有完成的任务", Toast.LENGTH_LONG).show();
		} else {
			tables = Table.doParse(str);
			wancenglist.clear();
			for (int j = 0; j < tables.length; j++) {
				RenWuClass rw = new RenWuClass();
				rw.setPaigongDan(tables[j].get("paigongdan").get(0));
				rw.setStartTime(tables[j].get("kaishiShijian").get(0));
				rw.setDate(tables[j].get("fuwuRiqi").get(0));
				rw.setCompany(tables[j].get("qiyemingcheng").get(0));
				rw.setAddress(tables[j].get("fuwuDidian").get(0));
				rw.setEndTime(tables[j].get("jiesuShijian").get(0));
				rw.setLine(tables[j].get("fuwuXianlu").get(0));
				rw.setType(tables[j].get("fuwumoshi").get(0));
				rw.setService(tables[j].get("fuwuleibie").get(0));
				rw.setState(tables[j].get("paigongdanstate").get(0));
				wancenglist.add(rw);
			}
			wanceng_list.setAdapter(adapter);
			adapter.updateList(wancenglist);
			if(app.size==0){
				huiku.setEnabled(true);
				huiku.setBackgroundResource(R.drawable.buttom_selector_bg);
			}else{
				huiku.setEnabled(false);
				huiku.setBackgroundResource(R.drawable.gray_btn_bg);
			}
		}
	}
	/**
	 * 传递信息
	 */
	public void passBox(){
		listBox.clear();
		String[] zzxBox = box.split(",");
		System.out.println("zzxBox:"+zzxBox);
		for (int j = 0; j < zzxBox.length; j++) {
			listBox.add(zzxBox[j].trim());
		}
		if(listBox.size()!=0){
			FragmentManager fm = getFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			FingerCheckFragment frag = new FingerCheckFragment();
			Bundle bundle = new Bundle();
			bundle.putSerializable("list", wancenglist);
			bundle.putSerializable("box", (Serializable) listBox);
			bundle.putString("cid", app.cardId);
			frag.setArguments(bundle);
			ft.addToBackStack(null);
			ft.replace(R.id.main_frame, frag).commit();
		}else{
			Toast.makeText(getActivity(), "周转箱为空", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 点击跳转 装箱明细页面
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		/**跳转页面*/
		FragmentTransaction ft = fm.beginTransaction();
		StartFwFragment fragment = new StartFwFragment();
		Bundle bundle = new Bundle();
		bundle.putString("cid", app.cardId);
		bundle.putSerializable("rw", (Serializable) wancenglist.get(arg2));
		fragment.setArguments(bundle);
		ft.addToBackStack(null);
		ft.replace(R.id.main_frame, fragment).commit();
	}
}
